<?php

namespace app\admin\controller\publicwelfare;

use app\common\controller\Backend;
use think\Db;

/**
 * 公益课程项目 控制器
 * 路由前缀: /publicwelfare/publicwelfare
 */
class Publicwelfare extends Backend
{
    // 允许未登录/无权限访问lists接口，便于下拉框异步加载
    protected $noNeedRight = ['lists'];
    protected $noNeedLogin = ['lists'];

    /**
     * 获取公益课程项目列表（模拟 coursetable/coursetable/lists 返回格式）
     * 入参(GET):
     * - cityId: 城市ID
     * - school_id: 学校ID（可选）
     * - community_id: 社区ID（可选）
     * - addresslv_id: 教学点等级/地点ID（可选）
     * 返回: {"list": [{"id": 1, "name": "项目A"}, ...]}
     */
    public function lists()
    {
        try {
            $cityId = $this->request->get('cityId/d', 0);
            $schoolId = $this->request->get('school_id/d', 0);
            $communityId = $this->request->get('community_id/d', 0);
            $addresslvId = $this->request->get('addresslv_id/d', 0);

            // 表名按前缀约定：fa_community_publicwelfare
            $query = Db::name('community_publicwelfare')->alias('p')
                ->field([Db::raw('p.id'), Db::raw("COALESCE(p.project_name, CONCAT('公益项目', p.id)) AS name")])
                ->where('p.status', '<>', -1)
                // 仅列出在正式排课表中出现过的公益项目
                ->whereExists(function($sub){
                    $sub->name('course_table_autoplan')->alias('t')
                        ->where('t.publicwelfare_id = p.id');
                });

            if ($cityId > 0 && $this->hasColumn('community_publicwelfare', 'city_id')) {
                $query->where('p.city_id', '=', $cityId);
            }
            if ($schoolId > 0 && $this->hasColumn('community_publicwelfare', 'school_id')) {
                $query->where('p.school_id', '=', $schoolId);
            }
            if ($communityId > 0 && $this->hasColumn('community_publicwelfare', 'community_id')) {
                $query->where('p.community_id', '=', $communityId);
            }
            if ($addresslvId > 0 && $this->hasColumn('community_publicwelfare', 'addresslv_id')) {
                $query->where('p.addresslv_id', '=', $addresslvId);
            }

            $list = $query->order('p.id', 'desc')->limit(100)->select();

            // 规范化输出
            $items = [];
            foreach ($list as $row) {
                $items[] = [
                    'id' => isset($row['id']) ? (int)$row['id'] : 0,
                    'name' => isset($row['name']) ? (string)$row['name'] : ('公益项目' . (isset($row['id']) ? $row['id'] : '')),
                ];
            }

            return json(['list' => $items]);
        } catch (\Throwable $e) {
            // 出错时返回空列表，避免前端报错
            return json(['list' => []]);
        }
    }

    /**
     * 判断数据表是否存在某字段（用于兼容不同环境的字段差异）
     */
    protected function hasColumn($table, $column)
    {
        try {
            $prefixed = Db::getTableInfo(Db::name($table)->getTable(), 'fields');
            return in_array($column, $prefixed, true);
        } catch (\Throwable $e) {
            return false;
        }
    }
}
